package com.ssh.multithread;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 线程池实现模型 lock-condition模型
 * 
 * @author zuoshuaiok@gmail.com
 * 
 */
public class WorkThread extends Thread {

	// public static void main(String[] args) {
	// WorkThread wt = new WorkThread();
	// wt.start();
	// for (int i = 0; i < 10; i++) {
	// wt.insertTask("--task--" + i);
	// }

	// ExecutorService executor=Executors.newFixedThreadPool(11);
	// executor.execute(new Runnable() {
	// @Override
	// public void run() {
	// // TODO Auto-generated method stub
	// System.out.println("----hello-----");
	// }
	// });
	// }

	private Queue<String> queue = new LinkedList<String>();

	private boolean isStop = false;

	private Lock lock = new ReentrantLock();

	private Condition isEmpty = lock.newCondition();

	public WorkThread(ThreadPool pool, int i) {
		this.setName("zuo-thread-" + i);
	}

	public WorkThread() {
	}

	public void insertTask(String task) {

		try {
			lock.lock();
			queue.add(task);
			isEmpty.signal();
		} finally {
			lock.unlock();
		}

	}

	@Override
	public void run() {

		while (!isStop) {

			try {

				lock.lock();
				while (queue.size() == 0) {
					try {
						System.out.println("----线程" + Thread.currentThread().getName() + "进入等待任务状态");
						isEmpty.await();
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

				String Task = queue.poll();
				System.out.println("----当前--" + Thread.currentThread().getName() + "--执行了任务---" + Task
						+ "-----finish----");
			} catch (Exception e) {
				// TODO: handle exception
				System.out.println("----error---");
			} finally {
				lock.unlock();
			}

		}

	}

}
